using System.Collections.Generic;
using UnityEngine;

namespace PhysSound
{
	[AddComponentMenu("PhysSound/PhysSound Terrain")]
	public class PhysSoundTerrain : PhysSoundBase
	{
		public Terrain Terrain;

		public List<PhysSoundMaterial> SoundMaterials = new List<PhysSoundMaterial>();

		private Dictionary<int, PhysSoundComposition> compDic = new Dictionary<int, PhysSoundComposition>();

		private TerrainData terrainData;

		private Vector3 terrainPos;

		private void Start()
		{
			terrainData = Terrain.terrainData;
			terrainPos = Terrain.transform.position;
			foreach (PhysSoundMaterial soundMaterial in SoundMaterials)
			{
				if (!compDic.ContainsKey(soundMaterial.MaterialTypeKey))
				{
					compDic.Add(soundMaterial.MaterialTypeKey, new PhysSoundComposition(soundMaterial.MaterialTypeKey));
				}
			}
		}

		public override PhysSoundMaterial GetPhysSoundMaterial(Vector3 contactPoint)
		{
			int dominantTexture = getDominantTexture(contactPoint);
			if (dominantTexture < SoundMaterials.Count && SoundMaterials[dominantTexture] != null)
			{
				return SoundMaterials[dominantTexture];
			}
			return null;
		}

		public Dictionary<int, PhysSoundComposition> GetComposition(Vector3 contactPoint)
		{
			foreach (PhysSoundComposition value2 in compDic.Values)
			{
				value2.Reset();
			}
			float[] textureMix = getTextureMix(contactPoint);
			for (int i = 0; i < textureMix.Length && i < SoundMaterials.Count; i++)
			{
				if (!(SoundMaterials[i] == null) && compDic.TryGetValue(SoundMaterials[i].MaterialTypeKey, out PhysSoundComposition value))
				{
					value.Add(textureMix[i]);
				}
			}
			return compDic;
		}

		private float[] getTextureMix(Vector3 worldPos)
		{
			float num = worldPos.x - terrainPos.x;
			Vector3 size = terrainData.size;
			int x = (int)(num / size.x * (float)terrainData.alphamapWidth);
			float num2 = worldPos.z - terrainPos.z;
			Vector3 size2 = terrainData.size;
			int y = (int)(num2 / size2.z * (float)terrainData.alphamapHeight);
			float[,,] alphamaps = terrainData.GetAlphamaps(x, y, 1, 1);
			float[] array = new float[alphamaps.GetUpperBound(2) + 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = alphamaps[0, 0, i];
			}
			return array;
		}

		private int getDominantTexture(Vector3 worldPos)
		{
			float[] textureMix = getTextureMix(worldPos);
			float num = 0f;
			int result = 0;
			for (int i = 0; i < textureMix.Length; i++)
			{
				if (textureMix[i] > num)
				{
					result = i;
					num = textureMix[i];
				}
			}
			return result;
		}
	}
}
